<script setup>
import { nextTick, ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getSongByIdApi, reportSongApi } from '@/api/song.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  deleteComment,
  getCommentList,
  saveOrUpdateComment
} from '@/api/comment.js'
import { useUserStore } from '@/stores/index.js'
import userImage from '@/assets/user.png'
import {
  cancelFollowUserApi,
  followUserApi,
  isFollowUserApi
} from '@/api/userFollow.js'
import { commentReport } from '@/api/commentReport.js'

const song = ref({
  title: 'Song Title',
  artist: 'Artist Name',
  duration: '3:45',
  lyrics: []
})

const songId = ref(0)
const route = useRoute()
const router = useRouter()

const init = async () => {
  try {
    if (!route.query?.songId) {
      ElMessage.error('歌曲不存在')
      return
    }
    songId.value = route.query?.songId
    const res = await getSongByIdApi(songId.value)
    song.value = res.data
    // 处理歌词
    song.value.lyrics = song.value.lyrics.map((item) => ({
      timestamp: Math.floor(item.time), // double -> int
      content: item.lineLyric
    }))
  } catch (error) {
    ElMessage.error('加载歌曲信息失败')
    console.error(error)
  }
}
// 歌词滚动
const audioElement = ref(null)
const currentTime = ref(0)
const activeIndex = ref(0)
const transformStyle = ref('')

function timeUpdateHandler() {
  currentTime.value = audioElement.value.currentTime
}
const muted = ref(false)
function canPlayHandler() {
  console.log('可以开始播放')
  const videoElement = document.getElementById('videoPlay')
  videoElement.play()
}

const audioChange = (i) => {
  audioElement.value.currentTime = i.timestamp + 1
}

nextTick(() => {
  // 获取box的高度
  let boxHeight = document.querySelector('.box').clientHeight / 2 - 150
  watch(currentTime, (newVal) => {
    const newActiveIndex =
      song.value.lyrics.findIndex((lyric) => lyric.timestamp > newVal) - 1
    if (newActiveIndex !== -1) {
      activeIndex.value = newActiveIndex
      transformStyle.value = `transform: translateY(${-activeIndex.value * 50 + boxHeight}px)`
    }
  })
})

// 评论
// 评论分页
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const getTableData = async () => {
  const res = await getCommentList({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    songId: songId.value
  })
  tableData.value = res.data['records']
  total.value = res.data.total
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  pageNum.value = val
  getTableData()
}
const comment = ref({
  songId: 0,
  content: ''
})
// 新增评论
const saveComment = async () => {
  if (songId.value === 0) {
    ElMessage.error('歌曲不存在')
    return
  }
  comment.value.songId = songId.value
  const res = await saveOrUpdateComment(comment.value)
  if (res?.code === 200) {
    comment.value.content = ''
    await getTableData()
    ElMessage.success('评论成功')
  } else {
    await router.push('/login')
  }
}
// 删除评论
const handelDeleteComment = async (id) => {
  ElMessageBox.confirm('确定删除该条评论吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteComment([id])
    await getTableData()
  })
}
watch(activeIndex, () => {
  let root = document.documentElement
  // 处理边界情况：当 activeIndex 为 0 时（第一句歌词）
  if (activeIndex.value === 0) {
    // 第一句持续时间可以设置为从 0 到第一个时间戳
    const firstLyricTime = song.value.lyrics[0].timestamp
    root.style.setProperty('--animation-duration', `${firstLyricTime}s`)
    return
  }

  // 处理最后一句歌词的情况
  if (activeIndex.value === song.value.lyrics.length - 1) {
    // 使用歌曲总时长或固定值（示例使用固定值 5s）
    const totalDuration = song.value.duration || 5
    const lastLyricTime = song.value.lyrics[activeIndex.value].timestamp
    root.style.setProperty(
      '--animation-duration',
      `${totalDuration - lastLyricTime}s`
    )
    return
  }

  // 常规情况：计算当前歌词与下一句歌词的时间差
  const current = song.value.lyrics[activeIndex.value].timestamp
  const next = song.value.lyrics[activeIndex.value + 1].timestamp
  const duration = (next - current).toFixed(2) // 不需要绝对值，时间戳应递增

  root.style.setProperty('--animation-duration', `${duration}s`)
})

const followUser = async () => {
  await followUserApi(song.value.user.id)
  await getIsFollow()
}
const disFollowUser = async () => {
  await cancelFollowUserApi(song.value.user.id)
  await getIsFollow()
}
const isFollow = ref(false)
const getIsFollow = async () => {
  const res = await isFollowUserApi(song.value.user.id)
  isFollow.value = res.data
}
onMounted(async () => {
  await init()
  await getIsFollow()
  await getTableData()
})
const reportSong = () => {
  ElMessageBox.confirm('确定举报该歌曲吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await reportSongApi(songId.value)
    await router.push('/home')
  })
}

const currentCommentId = ref(0)
const dialogVisible = ref(false)
const reportContent = ref('')
const handelReportComment = (id) => {
  dialogVisible.value = true
  currentCommentId.value = id
}
const submitReportComment = async () => {
  if (!/.{5,}/.test(reportContent.value)) {
    ElMessage.error('举报内容必须大于五个字')
    return
  }
  await commentReport({
    commentId: currentCommentId.value,
    reason: reportContent.value
  })
  dialogVisible.value = false
  reportContent.value = ''
  ElMessage.success('举报成功')
}
</script>

<template>
  <div class="song-detail-container">
    <h1>{{ song.name }} - {{ song.artist }}</h1>
    <div class="user-info">
      <div style="display: flex; align-items: center">
        <div class="user-details">
          <img
            :src="song.user?.avatar || userImage"
            alt="User Avatar"
            class="avatar"
          />
          <div class="username">{{ song.user?.username }}</div>
        </div>
        &emsp;
        <div
          class="user-actions"
          v-if="song.user?.id !== useUserStore().user.id"
        >
          <el-button
            type="primary"
            size="small"
            @click="followUser"
            v-if="!isFollow"
          >
            关注
          </el-button>
          <el-button v-else type="info" size="small" @click="disFollowUser">
            取消关注
          </el-button>
        </div>
      </div>

      <div class="user-report">
        <el-button type="danger" size="small" @click="reportSong"
          >举报该歌曲</el-button
        >
      </div>
    </div>
    <div
      class="box"
      :style="{
        backgroundImage: `url(${song.img})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
      }"
    >
      <div class="cd">
        <div class="msg">
          <ul :style="transformStyle">
            <li
              v-for="(item, index) in song.lyrics"
              :key="item.timestamp"
              :class="activeIndex === index ? 'active' : ''"
              @click="audioChange(item)"
            >
              {{ item.content }}
            </li>
          </ul>
        </div>
      </div>
      <video
        controls=""
        id="videoPlay"
        ref="audioElement"
        class="video"
        :src="song.songFileUrl"
        :muted="muted"
        @timeupdate="timeUpdateHandler"
        @canplay="canPlayHandler"
      ></video>
    </div>
  </div>
  <!-- 评论 -->
  <div class="comment">
    <el-card style="padding: 0; margin-top: 20px; border-radius: 25px">
      <template #header>发表评论</template>
      <!--   评论     -->
      <div class="comment_send">
        <div class="leave_comment">
          <img :src="useUserStore().user?.avatar" alt="用户" />
          <el-input
            v-model="comment.content"
            style="width: 50rem"
            :autosize="{ minRows: 6, maxRows: 6 }"
            type="textarea"
            placeholder="Please input"
          />
        </div>
        <el-button
          type="primary"
          style="
            float: right;
            margin-right: 1.5rem;
            margin-top: 1rem;
            margin-left: 6rem;
          "
          @click="saveComment"
          >发表评论</el-button
        >
      </div>

      <p>评论列表</p>
      <el-divider style="width: 120%; left: -2rem" />
      <!--   评论列表   -->
      <div v-for="item in tableData" :key="item.id" class="comment_list">
        <div class="comment_item">
          <img :src="item.avatar || userImage" alt="用户" />
          <div class="comment_content">
            <div class="comment_user">{{ item.username }}</div>
            <div class="comment_text">
              {{ item.content }}
            </div>
            <div class="comment_time">{{ item.createTime }}</div>
          </div>
          <div class="comment_delete">
            <el-button
              v-if="
                item.userId === useUserStore().user.id ||
                useUserStore().user.role === 'ADMIN'
              "
              type="danger"
              @click="handelDeleteComment(item.id)"
              >删除</el-button
            >
            <el-button
              v-if="item.userId !== useUserStore().user.id"
              type="warning"
              @click="handelReportComment(item.id)"
              >举报</el-button
            >
          </div>
        </div>
      </div>
      <!--   空评论列表     -->
      <el-empty v-if="tableData.length <= 0"></el-empty>
      <!--    分页    -->
      <template #footer>
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </template>
    </el-card>
  </div>
  <el-dialog v-model="dialogVisible" title="举报内容" width="500">
    <el-input v-model="reportContent" placeholder="请输入举报内容" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReportComment">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.song-detail-container {
  text-align: center;
  font-family: Arial, sans-serif;
}

.box {
  position: relative;
  border-radius: 0 0 25px 25px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  padding-top: 20px;
  /*边缘阴影*/
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.btn {
  padding: 12px 18px;
  border: none;
  border-radius: 30px;
  background-color: #84cce6;
  margin-bottom: 10px;
  color: #000;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.btn:hover {
  background-color: #5db8d6;
}

.video {
  width: 100%;
  height: 100px;
  position: absolute;
  bottom: 0;
  /*display: none;*/ /* 隐藏视频标签 */
}

.cd {
  margin-top: 30px;
  text-align: center;
  width: 80%;
}

.msg {
  width: 100%;
  height: 90vh;
  overflow: hidden;
  padding: 0 10px;
}

ul {
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.5s ease;
  padding: 0;
}

li {
  list-style: none;
  color: white;
  line-height: 50px;
  cursor: pointer;
  transition: transform 0.5s ease;
  font-size: 20px;
}
:root {
  --animation-duration: 2s;
}

li.active {
  font-weight: 1000;
  display: inline-block;
  font-size: 24px;
  position: relative;
  background-image: linear-gradient(
    90deg,
    white 0%,
    white 49%,
    #f9d982 50%,
    #f9d982 100%
  );
  background-size: 200% 100%;
  background-position: 100% 0;
  -webkit-background-clip: text;
  color: transparent;
  transform: scale(1.3);
  animation: color-change var(--animation-duration) linear forwards;
}

@keyframes color-change {
  0% {
    background-position: 0 100%;
  }
  100% {
    background-position: -100% 0;
  }
}

@media (max-width: 768px) {
  .cd img {
    width: 150px;
    height: 150px;
  }

  .box {
    padding: 20px;
  }
}

/*发布评论*/
.comment_send {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.leave_comment {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  img {
    width: 4rem;
    border-radius: 50%;
    margin: 1rem;
  }
}
/*评论列表*/
.comment_list {
  margin-top: 1rem;
  .comment_item {
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    align-items: flex-start;
    margin-bottom: 1rem;
    img {
      width: 3rem;
      border-radius: 50%;
      margin-right: 1rem;
    }
  }
  .comment_content {
    width: 48rem;
    .comment_user {
      margin-bottom: 0.5rem;
    }
  }
}
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 15px;
  background-color: #fff;
  padding: 15px;
  border-radius: 25px 25px 0 0;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

  .user-details {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
  }

  .username {
    font-size: 1.2rem;
    font-weight: bold;
    color: #333;
  }

  .follow-button {
    margin-left: auto;
    font-size: 0.9rem;
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.05);
    }

    &.el-button--primary {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
    }

    &.el-button--success {
      background-color: #67c23a;
      border-color: #67c23a;
      color: #fff;
    }
  }
}
</style>
